import SSHConfig from 'ssh2-promise/lib/sshConfig'
import { SSHResultType } from '../types'
import { SSHErrorCodeConst } from '../consts'
import { SSHErrorMsgMap } from '../maps'

/**
 * SSH 连接服务器时的错误处理
 *
 * @param err 错误对象
 * @param {SSHConfig} config SSH 连接服务器的配置对象
 * @returns {SSHResultType}
 */
export const errorHandler = (err: any, config: SSHConfig = {}): SSHResultType => {
  // 错误描述描述信息
  let message = '未知错误'
  // 错误详情
  let detail = ''
  if (err.code) {
    switch (err.code) {
      // 连接类错误
      case SSHErrorCodeConst.ECONNREFUSED:
        message = SSHErrorMsgMap[SSHErrorCodeConst.ECONNREFUSED].message
        detail = SSHErrorMsgMap[SSHErrorCodeConst.ECONNREFUSED].detail
        break
      case SSHErrorCodeConst.ETIMEDOUT:
        message = SSHErrorMsgMap[SSHErrorCodeConst.ETIMEDOUT].message
        detail = SSHErrorMsgMap[SSHErrorCodeConst.ETIMEDOUT].detail
        break
      case SSHErrorCodeConst.EHOSTUNREACH:
        message = SSHErrorMsgMap[SSHErrorCodeConst.EHOSTUNREACH].message
        detail = SSHErrorMsgMap[SSHErrorCodeConst.EHOSTUNREACH].detail
        break
      case SSHErrorCodeConst.EAUTH:
        message = SSHErrorMsgMap[SSHErrorCodeConst.EAUTH].message
        detail = SSHErrorMsgMap[SSHErrorCodeConst.EAUTH].detail
        break
      // 命令执行类错误
      case SSHErrorCodeConst.ENOENT:
        message = SSHErrorMsgMap[SSHErrorCodeConst.ENOENT].message
        detail = SSHErrorMsgMap[SSHErrorCodeConst.ENOENT].detail
        break
      case SSHErrorCodeConst.EACCES:
        message = SSHErrorMsgMap[SSHErrorCodeConst.EACCES].message
        detail = SSHErrorMsgMap[SSHErrorCodeConst.EACCES].detail
        break
      // SFTP 类错误
      case SSHErrorCodeConst.NO_SUCH_FILE:
        message = SSHErrorMsgMap[SSHErrorCodeConst.NO_SUCH_FILE].message
        detail = SSHErrorMsgMap[SSHErrorCodeConst.NO_SUCH_FILE].detail
        break
      case SSHErrorCodeConst.PERMISSION_DENIED:
        message = SSHErrorMsgMap[SSHErrorCodeConst.PERMISSION_DENIED].message
        detail = SSHErrorMsgMap[SSHErrorCodeConst.PERMISSION_DENIED].detail
        break
      // 未知错误
      default:
        message = SSHErrorMsgMap[SSHErrorCodeConst.UNKNOWN].message
        detail = SSHErrorMsgMap[SSHErrorCodeConst.UNKNOWN].detail + (' ' + err.stack || '')
        break
    }
  } else if (err.message?.includes('time out') || err.message?.includes('timed out')) {
    message = SSHErrorMsgMap[SSHErrorCodeConst.ETIMEDOUT].message
    detail = SSHErrorMsgMap[SSHErrorCodeConst.ETIMEDOUT].detail
  } else {
    message = SSHErrorMsgMap[SSHErrorCodeConst.UNKNOWN].message
    detail =
      SSHErrorMsgMap[SSHErrorCodeConst.UNKNOWN].detail + (' ' + err.message || JSON.stringify(err))
  }
  return {
    success: false,
    server: `${config.host || 'localhost'}:${config.port || 22}`,
    message,
    detail
  }
}

export type ErrorHandlerType = typeof errorHandler
